package com.dreamcode.anfeedreader.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dreamcode.anfeedreader.collectors.FeedsDAOimpl;
import com.dreamcode.anfeedreader.collectors.ItemObject;
import com.dreamcode.anfeedreader.modelClass.Feed;
import com.dreamcode.anfeedreader.modelClass.FeedItem;
import com.dreamcode.anfeedreader.utils.DateUtils;
import com.dreamcode.anfeedreader.utils.FeedParser;
import com.dreamcode.anfeedreader.utils.Message;
import com.dreamcode.anfeedreader.utils.XmlPullFeedParser;


public class AnFeedReader extends Activity {
    /** Called when the activity is first created. */
	private Button btnFeeds = null;
	private Button btnItems = null;
	private Button btnNew = null;
	private Button btnUpdate = null;
	private Button btnSettings = null;
	private Button btnAbout = null;
	private Button btnSearch = null;
	private FeedsDAOimpl feedsDAO = null;
	private LinearLayout feedContainer = null;
	private ItemObject itemObject = null;
	private Handler handler = new Handler();
	private List<ItemObject> itemObjectsList = null;
	private final static int EDIT_MODE = 1;
	private ProgressDialog progDialog = null; 
	private FeedParser parser = null;	
	private List<Message> messages;
	private Message feedMessage = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.anfeedmain);
        initView();
    }
    
    @Override
	protected void onResume() {
		super.onResume();
		itemObjectsList = feedsDAO.getItemObjectsByGroup(AnFeedReader.this);
    	itemObjectsList = feedsDAO.getAllNoneFeeds(AnFeedReader.this,itemObjectsList);
    	initFeedList(itemObjectsList);
	}

	public void initView(){
    	feedsDAO = FeedsDAOimpl.getInstance();
    	feedContainer = (LinearLayout) findViewById(R.id.feedscontainer);	
    	/*btnFeeds = (Button) findViewById(R.id.btnfeedlist);
    	btnFeeds.setEnabled(false);*/
    
    	/*btnItems = (Button) findViewById(R.id.btnitemlist);
    	btnItems.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(AnFeedReader.this, RelevantFeedItems.class);
				startActivity(i);
			}
		});*/
    	
    	btnNew = (Button) findViewById(R.id.btnnew);
    	btnNew.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(AnFeedReader.this,NewFeedActivity.class);				
				startActivity(i);				
			}
		});
    	btnUpdate = (Button) findViewById(R.id.btnupdate);
    	btnUpdate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//			    progDialog = new ProgressDialog(AnFeedReader.this);
//			    progDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//			    progDialog.setMessage("Loading");
//			    progDialog.incrementProgressBy(5);
//			    progDialog.show();
//				Thread thread = new Thread(this);
//				thread.start();
				progDialog = ProgressDialog.show(AnFeedReader.this, "", (CharSequence)Html.fromHtml(getString(R.string.update_wait)), true);
				handler.postDelayed(updatingRunnable,10000);
				//updateAllFeeds();				
				/*itemObjectsList = feedsDAO.getItemObjectsByGroup(AnFeedReader.this);
		    	itemObjectsList = feedsDAO.getAllNoneFeeds(AnFeedReader.this,itemObjectsList);
		    	initFeedList(itemObjectsList);*/
			}
		});
/*    	btnSettings = (Button) findViewById(R.id.btnset);
    	btnSettings.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(AnFeedReader.this, AccountSettingsActivity.class);
				startActivity(i);
				
			}
		});*/
    	btnAbout = (Button) findViewById(R.id.btnabout);
    	btnAbout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				AlertDialog groupDialog = new AlertDialog.Builder(AnFeedReader.this).setTitle("AnFeedReader")
				.setMessage("Version : 0.1\nDevelopment:\nZarko Popovski\nLazar Pancevski")
				.setPositiveButton("OK", null).show();		
				
			}
		});
    	
/*    	btnSearch = (Button) findViewById(R.id.btnitemsearch);
    	btnSearch.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(AnFeedReader.this, SearchFeedItemsActivity.class);
				startActivity(i);
			}
		});*/
    	
    	itemObjectsList = feedsDAO.getItemObjectsByGroup(AnFeedReader.this);
    	itemObjectsList = feedsDAO.getAllNoneFeeds(AnFeedReader.this,itemObjectsList);
    	initFeedList(itemObjectsList);
    }
    
    public void initFeedList(List<ItemObject> itemObjectsList){
    	feedContainer.removeAllViews();
    	for(int i=0;i<itemObjectsList.size();i++){
    		itemObject = itemObjectsList.get(i);
    		feedContainer.addView(generateView(itemObject));  
    	}
    }
    private Runnable progressDialog = new Runnable() {

        public void run() {
            ProgressDialog dialog = ProgressDialog.show(AnFeedReader.this, "", (CharSequence)Html.fromHtml(getString(R.string.update_wait)), true);
        }

    };

    private Runnable updatingRunnable = new Runnable() {
    		
    	public void run() {
    		//ProgressDialog dialog = ProgressDialog.show(AnFeedReader.this, "", (CharSequence)Html.fromHtml(getString(R.string.update_wait)), true);
    		updateAllFeeds();
    		progDialog.dismiss();
    		itemObjectsList = feedsDAO.getItemObjectsByGroup(AnFeedReader.this);
	    	itemObjectsList = feedsDAO.getAllNoneFeeds(AnFeedReader.this,itemObjectsList);
	    	initFeedList(itemObjectsList);
    	}
    };
    
    public LinearLayout generateView(ItemObject itemObject){
    	LinearLayout containerLayout = new LinearLayout(AnFeedReader.this);
    	final LinearLayout elmHolder = new LinearLayout(AnFeedReader.this);
    	elmHolder.setOrientation(LinearLayout.HORIZONTAL);
    	TextView tV = new TextView(AnFeedReader.this);    	
    	TextView tVsize = new TextView(AnFeedReader.this);
    	ImageView favIconView = new ImageView(AnFeedReader.this);
    	ImageView arrowView = new ImageView(AnFeedReader.this);
    	favIconView.setMaxHeight(32);
	    favIconView.setMaxWidth(32);
    	byte [] favIconData = null;
    	List<FeedItem>tempList = null;
    	if(itemObject.getType().equals("label")){    	    
    	    tV.setText(itemObject.getItemName());
    	    tV.setHeight(20);    	    
    	    tV.setTextColor(Color.RED);
    	    tV.setGravity(Gravity.CENTER_VERTICAL);
    	    containerLayout.addView(tV);
    	    containerLayout.setBackgroundResource(R.drawable.grbg);
    	}else if(itemObject.getType().equals("feed")){
    		tempList = feedsDAO.getAllFeedItemsFromDB(AnFeedReader.this, itemObject.getId());
    	    tV.setText(itemObject.getItemName());
    	    tV.setTextColor(Color.BLACK);  
    	    tV.setHeight(40);
    	    tV.setWidth(230);
    	    tV.setGravity(Gravity.CENTER_VERTICAL);    	    
    	    tVsize.setWidth(65);    	    
    	    tVsize.setText(calcFeedItems(tempList));
    	    tVsize.setTextColor(Color.BLACK);
    	    tVsize.setTextSize(12);
    	    tVsize.setGravity(Gravity.RIGHT);
    	    if(itemObject.getFavIconData()!=null){
    	    	favIconView.setImageBitmap(BitmapFactory.decodeByteArray(itemObject.getFavIconData(), 0, itemObject.getFavIconData().length));    	    	   	    	
    	    }
    	    else{
    	    	favIconView.setBackgroundResource(R.drawable.default_favicon);
    	    	tV.setWidth(198); 
    	    }
    	    arrowView.setBackgroundResource(R.drawable.arrow_new2);
    	    arrowView.setPadding(20, 20, 20, 20);
    	    elmHolder.addView(favIconView);
    	    elmHolder.addView(tV);
    	    elmHolder.addView(tVsize);
    	    elmHolder.setBackgroundResource(R.drawable.bg_color5);
    	    elmHolder.addView(arrowView);
    	    elmHolder.setPadding(1, 1, 1, 1);
    	    elmHolder.setId(itemObject.getId());
    	    elmHolder.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                	if(feedsDAO.checkFeedExistence(AnFeedReader.this, elmHolder.getId())){
	                	Intent i = new Intent(AnFeedReader.this,FeedItemListActivity.class);
	                	i.putExtra("id", elmHolder.getId());
	                	startActivity(i);
                	}else{
                        Toast.makeText(AnFeedReader.this, (CharSequence)Html.fromHtml(getString(R.string.empty_feed)), Toast.LENGTH_LONG).show();
                	}
                }
            });
    	    elmHolder.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					createDialogEdit(elmHolder.getId());
					//Toast.makeText(AnFeedReader.this, "On Long Click Id No: "+elmHolder.getId(), Toast.LENGTH_LONG).show();					
					return true;
				}

			});
    	    containerLayout.addView(elmHolder);    	  
    	    //containerLayout.setBackgroundResource(R.drawable.fgbg);
    	    containerLayout.setBackgroundColor(Color.BLACK);
    	}
    	
    	return containerLayout;
    }

    public String calcFeedItems(List<FeedItem>tempList){
    	int unReadCnt = 0;
    	for(int i=0;i<tempList.size();i++){
    		if(((tempList.get(i)).getStatus()).equals("0"))
    			unReadCnt++;  
    	}
    	return unReadCnt+" Unread";
    }
    
    private void createDialogEdit(final int id) {
    	final LinearLayout container = new LinearLayout(AnFeedReader.this);
		container.setOrientation(LinearLayout.VERTICAL);
		final Button editBtn = new Button(AnFeedReader.this);
		final Button deleteBtn = new Button(AnFeedReader.this);
		final Button cancelBtn = new Button(AnFeedReader.this);
		editBtn.setText(R.string.edit);
		deleteBtn.setText(R.string.delete);
		cancelBtn.setText(R.string.cancel);
		container.addView(editBtn);
		container.addView(deleteBtn);
		container.addView(cancelBtn);
    	final AlertDialog groupDialog = new AlertDialog.Builder(this).setTitle(R.string.edit_feed).setView(container).show();
    	editBtn.setOnClickListener(new OnClickListener() {

    		@Override
			public void onClick(View v) {
				Intent i = new Intent(AnFeedReader.this,NewFeedActivity.class);    
				i.putExtra("mode", EDIT_MODE);
				i.putExtra("id", id);
				    startActivity(i);
				    groupDialog.dismiss();
			}
		});
    	deleteBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				createYesNoDialog(id);
				groupDialog.dismiss();
			}
		});
    	cancelBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				groupDialog.dismiss();
			}
		});
		
	}
    
	private void createYesNoDialog(final int id) {
		final LinearLayout container = new LinearLayout(AnFeedReader.this);
		container.setOrientation(LinearLayout.VERTICAL);
		final AlertDialog groupDialog = new AlertDialog.Builder(this).setTitle(R.string.question1).setView(container)
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				feedsDAO.deleteFeed(AnFeedReader.this, id);
				initView();
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).show();
	}
	
	private void updateAllFeeds() {		
		List<Feed> feeds = feedsDAO.getAllFeeds(this);
		if(feeds.size()>0){
			Iterator iterator = feeds.iterator();
			Feed feed = null;
			FeedItem feedItem = null;
			Date crDate = null;
			String formatedDate;
			SimpleDateFormat sdFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm zzzz");
			while(iterator.hasNext()) {
				feed = (Feed) iterator.next();
				if (feed.getUrl() != null) {
					parser = new XmlPullFeedParser(feed.getUrl());
					messages = parser.parse();
					if(messages!=null && messages.size()>0) {
						crDate = new Date();
						formatedDate = sdFormat.format(crDate);
						for (int i = 0; i < messages.size(); i++) {
							feedMessage = messages.get(i);				
							if(feedMessage.getTitle()!=null && feedMessage.getLink()!=null){								
								feedItem = new FeedItem();
								feedItem.setTitle(feedMessage.getTitle());
								feedItem.setDescription(feedMessage.getDescription());
								feedItem.setLink(feedMessage.getLink().toString());
								feedItem.setPubDate(DateUtils.formatDate(DateUtils.parseDate((feedMessage.getDate()!=null)?feedMessage.getDate():formatedDate)));
								feedItem.setFeed_id(feed.getId());
								feedItem.setMd5hash(feedsDAO.getMd5Hash(feedItem.getLink()));
								feedItem.setStatus("0");
								if(!feedsDAO.checkItemExistence(this,feedItem)) {
									feedsDAO.insertFeedItems(this, feedItem);
								}
							}
						}
					}
					else {
						AlertDialog groupDialog = new AlertDialog.Builder(AnFeedReader.this).setTitle(R.string.invalid_url)
						.setMessage(R.string.invalid_url_message + feed.getUrl() + R.string.check_it_again + feed.getUrl())
						.setPositiveButton(R.string.ok, null).show();
						initView();
					}
				}
			}	
		}else{
			Toast.makeText(AnFeedReader.this, (CharSequence)Html.fromHtml(getString(R.string.empty_list)), Toast.LENGTH_SHORT).show();
		}
	}

}